import React, { useState, useEffect, Suspense } from 'react';
import { Layout, Menu, Button, Dropdown, Avatar, Space } from 'antd';
import {
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  BookOutlined,
  SettingOutlined,
  FileDoneOutlined,
  TrophyOutlined,
  UserOutlined,
  TeamOutlined,
  QuestionCircleOutlined,
  DashboardOutlined,
  FileOutlined,
  LogoutOutlined,
  MenuOutlined,
  AppstoreOutlined,
} from '@ant-design/icons';
import { Outlet, useNavigate, useLocation} from 'react-router-dom';
import { useAuthStore, AdminType } from '@/store/useAuthStore';
import './AdminLayout.css';
import BreadcrumbNav from '@/components/Breadcrumb';
import LoadingSpinner from '@/components/LoadingSpinner';
import { useSubNav } from '@/hooks/useSubNav';
import type { MenuProps } from 'antd';
import { useWebsiteStore } from '@/store/useWebsiteStore';
import DocumentTitle from '@/components/DocumentTitle';
import http from '@/http';
import { accountService } from '@/services/accountService';

const { Header, Sider, Content } = Layout;

const AdminLayout: React.FC = () => {
  const [collapsed, setCollapsed] = useState(false);
  const [avatarUrl, setAvatarUrl] = useState<string | undefined>(undefined);
  const navigate = useNavigate();
  const location = useLocation();
  const { isAuthenticated, clearAuth, user, isAdmin } = useAuthStore();

  // 直接使用配置
  const { config } = useWebsiteStore();
  const websiteName = config?.website_name_shortcut || 'OJ';

  // 检查是否是管理首页
  const isAdminHomePage = location.pathname === '/admin';

  // 获取用户头像
  useEffect(() => {
    if (isAuthenticated && user) {
      const fetchAvatar = async () => {
        try {
          const response = await accountService.getProfile();
          if (response.data && response.data.avatar) {
            setAvatarUrl(response.data.avatar);
          }
        } catch (error) {
          console.error('获取用户头像失败:', error);
        }
      };
      
      fetchAvatar();
    }
  }, [isAuthenticated, user]);

  // 顶部导航项
  const topMenuItems = [
    { key: '/admin/', label: '管理控制台', icon: <DashboardOutlined /> },
    { key: '/admin/problem', label: '题目管理', icon: <BookOutlined /> },
    { key: '/admin/submission', label: '提交管理', icon: <FileDoneOutlined /> },
    { key: '/admin/contest', label: '比赛管理', icon: <TrophyOutlined /> },
    { key: '/admin/paper', label: '试卷管理', icon: <FileOutlined /> },
    { key: '/admin/question', label: '问题管理', icon: <QuestionCircleOutlined /> },
    { key: '/admin/content/articles', label: '内容管理', icon: <AppstoreOutlined /> },
    { key: '/admin/user/list', label: '用户管理', icon: <TeamOutlined /> },
  ];
  
  // 超级管理员才能看到系统设置选项
  if (user?.admin_type === AdminType.SUPER_ADMIN) {
    topMenuItems.push({ key: '/admin/setting', label: '系统配置', icon: <SettingOutlined /> });
  }

  // 处理顶部导航点击
  const handleTopMenuClick = ({ key }: { key: string }) => {
    navigate(key);
  };

  // 处理登出
  const handleLogout = () => {
    setAvatarUrl(undefined);
    navigate('/logout');
  };

  // 切换到用户端
  const switchToUser = () => {
    navigate('/');
  };

  const { subNavItems, selectedKey } = useSubNav();

  // 管理员菜单项
  let adminMenuItems: MenuProps['items'] = [
    {
      key: 'switchToUser',
      label: '切换到用户端',
      onClick: switchToUser,
    },
    {
      type: 'divider',
    },
    {
      key: 'logout',
      label: '退出登录',
      icon: <LogoutOutlined />,
      onClick: handleLogout,
    },
  ];
  
  // 超级管理员才能看到系统配置选项
  if (user?.admin_type === AdminType.SUPER_ADMIN) {
    adminMenuItems = [
      adminMenuItems[0],
      {
        key: 'systemSetting',
        label: '系统配置',
        icon: <SettingOutlined />,
        onClick: () => navigate('/admin/setting'),
      },
      ...adminMenuItems.slice(1)
    ];
  }

  // 未登录用户的菜单项
  const guestMenuItems: MenuProps['items'] = [
    {
      key: 'login',
      label: '登录',
      onClick: () => navigate('/login'),
    },
    {
      key: 'register',
      label: '注册',
      onClick: () => navigate('/register'),
    },
  ];

  return (
    <Layout style={{ minHeight: '100vh' }}>
      <DocumentTitle title="管理系统" useShortcut={true} />
      <Header style={{ padding: 0, background: '#fff', height: '48px', lineHeight: '48px' }}>
        <div className="header-content">
          <div className="logo">{websiteName}管理系统</div>
          <Menu
            mode="horizontal"
            selectedKeys={[location.pathname]}
            items={topMenuItems}
            onClick={handleTopMenuClick}
            style={{ flex: 1 }}
          />
          <div className="header-right">
            {isAuthenticated ? (
              <Dropdown menu={{ items: adminMenuItems }} placement="bottomRight">
                <Space className="admin-dropdown">
                  <Avatar 
                    size="default" 
                    icon={<UserOutlined />}
                    src={avatarUrl ? http.getAvatarUrl(avatarUrl) : undefined}
                    style={{ backgroundColor: '#1677ff' }}
                  />
                  <span>{user?.username || '用户'}</span>
                </Space>
              </Dropdown>
            ) : (
              <Dropdown menu={{ items: guestMenuItems }} placement="bottomRight">
                <Button type="text" icon={<MenuOutlined />} />
              </Dropdown>
            )}
          </div>
        </div>
      </Header>
      <Layout>
        {!isAdminHomePage && (
          <Sider 
            trigger={null} 
            collapsible 
            collapsed={collapsed}
            theme="light"
          >
            <Button
              type="text"
              icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
              onClick={() => setCollapsed(!collapsed)}
              style={{
                fontSize: '14px',
                width: '100%',
                height: 40,
                borderRadius: 0,
                border: 'none',
                borderBottom: '1px solid #f0f0f0'
              }}
            />
            <Menu
              mode="inline"
              selectedKeys={[selectedKey]}
              items={subNavItems}
              onClick={({ key }) => navigate(key)}
            />
          </Sider>
        )}
        <Layout>
          {!isAdminHomePage && (
            <div className="admin-breadcrumb-container">
              <BreadcrumbNav />
            </div>
          )}
          <Content style={{ margin: '0 16px', padding: isAdminHomePage ? 0 : 24 }}>
            <Suspense fallback={<LoadingSpinner tip="加载管理功能..." />}>
              <Outlet />
            </Suspense>
          </Content>
        </Layout>
      </Layout>
    </Layout>
  );
};

export default AdminLayout;
